package scan

import (
	"Suscan/models"
	"Suscan/pkg/utils"
	"context"
	"fmt"
	"github.com/Ullaakut/nmap/v2"
	"log"
	"strconv"
	"strings"
	"time"
)
//arget.Ip, target.Port, id_url
func IpNmap(ip, port string,url string) {
	var (
		resultBytes []byte
		errorBytes  []byte
	)

	ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Minute)
	defer cancel()

	s, err := nmap.NewScanner(
		nmap.WithTargets(ip),
		nmap.WithPorts(port),
		nmap.WithContext(ctx),
		nmap.WithSkipHostDiscovery(),
		nmap.WithServiceInfo(),
	)
	if err != nil {
		log.Fatalf("unable to create nmap scanner: %v", err)
	}

	if err := s.RunAsync(); err != nil {
		return
	}

	stdout := s.GetStdout()

	stderr := s.GetStderr()

	go func() {
		for stdout.Scan() {
			resultBytes = append(resultBytes, stdout.Bytes()...)
		}
	}()

	go func() {
		for stderr.Scan() {
			errorBytes = append(errorBytes, stderr.Bytes()...)
		}
	}()

	if err := s.Wait(); err != nil {
		return
	}

	result, err := nmap.Parse(resultBytes)

	result.NmapErrors = strings.Split(string(errorBytes), "\n")

	if err != nil {
		return
	}

	for _, host := range result.Hosts {
		if len(host.Ports) == 0 || len(host.Addresses) == 0 {
			continue
		}
		for _, port := range host.Ports {
			//格式化nmap扫描返回的字段为string
			//hostname := fmt.Sprintf("%s", host.Hostnames)
			//context := strings.Fields(hostname)
			//hostname = context[0]
			//hostname = strings.Trim(hostname, "[")
			//hostname = strings.Trim(hostname, "]")

			ip := fmt.Sprintf("%s", host.Addresses[0])
			portchange := strconv.Itoa(int(port.ID))
			service := fmt.Sprintf("%s", port.Service)

			url1 := utils.ParseUrl(url, portchange)
			for _, results := range utils.Identify(url1, 5) {
				fmt.Println("识别ip的results为： ")
				fmt.Println(results)
				data := make(map[string]interface{})
				nowTime := time.Now().Format("2006-01-02 15:04:05")
				data["url"]= url
				data["ip"] = ip
				data["port"] = portchange
				data["protocol"] = port.Protocol
				data["service"] = service
				data["status"]=port.State.State
				data["res_code"] = results.RespCode
				data["res_result"] = results.Result
				data["res_type"] = results.Type
				data["res_url"] = results.Url
				data["res_title"] = results.Title
				data["login_url"] = ""
				data["title"] = ""
				data["updated_time"] = nowTime
				models.AddIplist(data)
				return
			}
		}
	}

}
